package cn.powerone.scm.service.impl;

import java.math.BigDecimal;
import java.util.List;

import cn.powerone.common.exception.ServiceException;
import cn.powerone.common.utils.DateUtils;
import cn.powerone.common.utils.StringUtils;
import cn.powerone.scm.domain.ScmEstimateQuotes;
import cn.powerone.scm.domain.ScmInquiriesOut;
import cn.powerone.scm.domain.ScmProjects;
import cn.powerone.scm.service.IScmEstimateQuotesService;
import cn.powerone.scm.service.IScmInquiriesOutService;
import cn.powerone.scm.service.IScmProjectsService;
import cn.powerone.scm.upload.domain.ScmImportInquiriesIn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.powerone.scm.mapper.ScmSupplierQuotesMapper;
import cn.powerone.scm.domain.ScmSupplierQuotes;
import cn.powerone.scm.service.IScmSupplierQuotesService;

/**
 * 供应商报价单Service业务层处理
 * 
 * @author PowerOne
 * @date 2025-07-03
 */
@Service
public class ScmSupplierQuotesServiceImpl implements IScmSupplierQuotesService 
{
    @Autowired
    private ScmSupplierQuotesMapper scmSupplierQuotesMapper;

    @Autowired
    private IScmInquiriesOutService scmInquiriesOutService;
    @Autowired
    private IScmEstimateQuotesService scmEstimateQuotesService;
    @Autowired
    private IScmProjectsService scmProjectsService;

    /**
     * 查询供应商报价单
     * 
     * @param id 供应商报价单主键
     * @return 供应商报价单
     */
    @Override
    public ScmSupplierQuotes selectScmSupplierQuotesById(Long id)
    {
        return scmSupplierQuotesMapper.selectScmSupplierQuotesById(id);
    }

    /**
     * 查询供应商报价单列表
     * 
     * @param scmSupplierQuotes 供应商报价单
     * @return 供应商报价单
     */
    @Override
    public List<ScmSupplierQuotes> selectScmSupplierQuotesList(ScmSupplierQuotes scmSupplierQuotes)
    {
        return scmSupplierQuotesMapper.selectScmSupplierQuotesList(scmSupplierQuotes);
    }

    /**
     * 新增供应商报价单
     * 
     * @param scmSupplierQuotes 供应商报价单
     * @return 结果
     */
    @Override
    public int insertScmSupplierQuotes(ScmSupplierQuotes scmSupplierQuotes)
    {
        scmSupplierQuotes.setCreateTime(DateUtils.getNowDate());
        return scmSupplierQuotesMapper.insertScmSupplierQuotes(scmSupplierQuotes);
    }

    /**
     * 修改供应商报价单
     * 
     * @param scmSupplierQuotes 供应商报价单
     * @return 结果
     */
    @Override
    public int updateScmSupplierQuotes(ScmSupplierQuotes scmSupplierQuotes)
    {
        scmSupplierQuotes.setUpdateTime(DateUtils.getNowDate());
        return scmSupplierQuotesMapper.updateScmSupplierQuotes(scmSupplierQuotes);
    }

    /**
     * 批量删除供应商报价单
     * 
     * @param ids 需要删除的供应商报价单主键
     * @return 结果
     */
    @Override
    public int deleteScmSupplierQuotesByIds(Long[] ids)
    {
        return scmSupplierQuotesMapper.deleteScmSupplierQuotesByIds(ids);
    }

    /**
     * 删除供应商报价单信息
     * 
     * @param id 供应商报价单主键
     * @return 结果
     */
    @Override
    public int deleteScmSupplierQuotesById(Long id)
    {
        return scmSupplierQuotesMapper.deleteScmSupplierQuotesById(id);
    }

    @Override
    public int createScmSupplierQuotes(Long projectId) {
        ScmProjects scmProjects = scmProjectsService.selectScmProjectsByProjectId(projectId);

        ScmInquiriesOut condition = new ScmInquiriesOut();
        condition.setProjectId(projectId);
        List<ScmInquiriesOut> list = scmInquiriesOutService.selectScmInquiriesOutList(condition);
        // 遍历 返回list，组装和创建供应商报价单
        ScmSupplierQuotes scmSupplierQuotes = new ScmSupplierQuotes();
        int rows = 0;
        for (ScmInquiriesOut item : list) {
            //查询报价单里是否已经存在对应的询价记录
            if (scmSupplierQuotesMapper.selectScmSupplierQuotesByInquiryId(item.getId()) != null){
                continue;
            }
            //组装和创建报价单
            scmSupplierQuotes.setProjectId(item.getProjectId());
            scmSupplierQuotes.setProductId(item.getProductId());
            scmSupplierQuotes.setProjectProductId(item.getProjectProductId());
            scmSupplierQuotes.setDrawingNumber(item.getDrawingNumber());
            scmSupplierQuotes.setInternalVersion(item.getInternalVersion());
            scmSupplierQuotes.setSupplierId(item.getSupplierId());
            scmSupplierQuotes.setInquiryId(item.getId());
            scmSupplierQuotes.setSupplierName(item.getSupplierName());
            scmSupplierQuotes.setInquiryDate(DateUtils.getNowDate());
            scmSupplierQuotes.setDrawingMaterial("?");
            scmSupplierQuotes.setMaterial(item.getMaterial());
            scmSupplierQuotes.setInflamingRetardingLevel("?");
            scmSupplierQuotes.setTaxIncluded("Y");
            scmSupplierQuotes.setFreightIncluded("Y");
            scmSupplierQuotes.setDisposableQuantity(item.getDisposableQuantity());
            scmSupplierQuotes.setDisposableUnit(item.getDisposableUnit());
            scmSupplierQuotes.setDisposableUnitPrice(BigDecimal.valueOf(0));
            scmSupplierQuotes.setTryLot(item.getTryQuantity());
            scmSupplierQuotes.setTryUnit(item.getTryUnit());
            scmSupplierQuotes.setTryUnitPrice(BigDecimal.valueOf(0));
            scmSupplierQuotes.setMassLot(item.getMassQuantity());
            scmSupplierQuotes.setMassUnit(item.getMassUnit());
            scmSupplierQuotes.setMassUnitPrice(BigDecimal.valueOf(0));
            scmSupplierQuotes.setMoldCost(BigDecimal.valueOf(0));
            scmSupplierQuotes.setJigCost(BigDecimal.valueOf(0));
            scmSupplierQuotes.setMoldTryingDeliveryDays(0L);
            scmSupplierQuotes.setMoldLife(0L);
            scmSupplierQuotes.setDisposableDeliveryDays(0L);
            scmSupplierQuotes.setTryDeliveryDays(0L);
            scmSupplierQuotes.setMassDeliveryDays(0L);
            scmSupplierQuotes.setStatus(0L);
            scmSupplierQuotes.setSupplierCurrency(scmProjects.getSupplierCurrency());
            scmSupplierQuotes.setSupplierCurrencyRate(scmProjects.getSupplierCurrencyRate());
            rows  += scmSupplierQuotesMapper.insertScmSupplierQuotes(scmSupplierQuotes);

        }
        return rows;
    }

    /**
     *  更新供应商报价单状态
     * @param ids
     * @param scmSupplierQuotes
     * @return
     */
    @Override
    public int updateStatusScmSupplierQuotesByIds(Long[] ids, ScmSupplierQuotes scmSupplierQuotes) {
        if (scmSupplierQuotes.getStatus() != 1 && scmSupplierQuotes.getStatus() != 2 && scmSupplierQuotes.getStatus() != 3){
            return 0;
        }
        //遍历ids， 并从数据库中查询，获取对应的供应商报价单
        ScmSupplierQuotes tempQuote;
        ScmEstimateQuotes scmEstimateQuotes;
        int rows = 0;
        for (Long id : ids) {
            tempQuote = scmSupplierQuotesMapper.selectScmSupplierQuotesById(id);
            // 更新报价单状态
            if (tempQuote == null){
                continue;
            }
            tempQuote.setStatus(scmSupplierQuotes.getStatus());
            tempQuote.setStatusReason(scmSupplierQuotes.getStatusReason());
            rows  += scmSupplierQuotesMapper.updateScmSupplierQuotes(tempQuote);

            scmEstimateQuotes = scmEstimateQuotesService.selectScmEstimateQuotesBySupplierQuoteId(tempQuote.getId());
            // 如果报价单状态为1，则生成对应的ScmEstimateQuotes
            if (scmSupplierQuotes.getStatus() == 1){
                if (scmEstimateQuotes == null){
                    scmEstimateQuotes = new ScmEstimateQuotes();
                    scmEstimateQuotes.setProjectId(tempQuote.getProjectId());
                    scmEstimateQuotes.setProductId(tempQuote.getProductId());
                    scmEstimateQuotes.setProjectProductId(tempQuote.getProjectProductId());
                    scmEstimateQuotes.setDrawingNumber(tempQuote.getDrawingNumber());
                    scmEstimateQuotes.setInternalVersion(tempQuote.getInternalVersion());
                    scmEstimateQuotes.setSupplierId(tempQuote.getSupplierId());
                    scmEstimateQuotes.setSupplierQuoteId(tempQuote.getId());
                    scmEstimateQuotes.setSupplierName( tempQuote.getSupplierName());
                    scmEstimateQuotes.setQuoteDate(tempQuote.getQuoteDate());
                    scmEstimateQuotes.setDrawingMaterial(tempQuote.getDrawingMaterial());
                    scmEstimateQuotes.setMaterial(tempQuote.getMaterial());
                    scmEstimateQuotes.setInflamingRetardingLevel(tempQuote.getInflamingRetardingLevel());
                    scmEstimateQuotes.setTaxIncluded(tempQuote.getTaxIncluded());
                    scmEstimateQuotes.setFreightIncluded(tempQuote.getFreightIncluded());
                    scmEstimateQuotes.setDisposableQuantity(tempQuote.getDisposableQuantity());
                    scmEstimateQuotes.setDisposableUnit(tempQuote.getDisposableUnit());
                    scmEstimateQuotes.setDisposableUnitPrice(tempQuote.getDisposableUnitPrice());
                    scmEstimateQuotes.setTryLot(tempQuote.getTryLot());
                    scmEstimateQuotes.setTryUnit(tempQuote.getTryUnit());
                    scmEstimateQuotes.setTryUnitPrice(tempQuote.getTryUnitPrice());
                    scmEstimateQuotes.setTryTotalPrice(tempQuote.getTryTotalPrice());
                    scmEstimateQuotes.setMassLot(tempQuote.getMassLot());
                    scmEstimateQuotes.setMassUnit(tempQuote.getMassUnit());
                    scmEstimateQuotes.setMassUnitPrice(tempQuote.getMassUnitPrice());
                    scmEstimateQuotes.setMoldCost(tempQuote.getMoldCost());
                    scmEstimateQuotes.setJigCost(tempQuote.getJigCost());
                    scmEstimateQuotes.setMoldTryingDeliveryDays(tempQuote.getMoldTryingDeliveryDays());
                    scmEstimateQuotes.setMoldLife(tempQuote.getMoldLife());
                    scmEstimateQuotes.setDisposableDeliveryDays(tempQuote.getDisposableDeliveryDays());
                    scmEstimateQuotes.setTryDeliveryDays(tempQuote.getTryDeliveryDays());
                    scmEstimateQuotes.setMassDeliveryDays(tempQuote.getMassDeliveryDays());
                    scmEstimateQuotes.setStatus(0L);
                    scmEstimateQuotes.setStatusReason(scmSupplierQuotes.getStatusReason());
                    scmEstimateQuotes.setSupplierCurrency(tempQuote.getSupplierCurrency());
                    scmEstimateQuotes.setSupplierCurrencyRate(tempQuote.getSupplierCurrencyRate());
                    scmEstimateQuotesService.insertScmEstimateQuotes(scmEstimateQuotes);
                }
//                else if (scmEstimateQuotes.getStatus() != 1){
//                    scmEstimateQuotes.setStatus(1L);
//                    scmEstimateQuotes.setStatusReason(scmSupplierQuotes.getStatusReason());
//                    scmEstimateQuotesService.updateScmEstimateQuotes(scmEstimateQuotes);
//                }
            }

            // 如果状态为2 or 3，则查询ScmEstimateQuotes中是否存在对应记录，如果存在，则修改ScmEstimateQuotes中记录状态为2 or 3
            if (scmSupplierQuotes.getStatus() == 2 || scmSupplierQuotes.getStatus() == 3){
                if (scmEstimateQuotes == null){
                    break;
                } else if (scmEstimateQuotes.getStatus() != 2 && scmEstimateQuotes.getStatus() != 3){
                    scmEstimateQuotes.setStatus( scmSupplierQuotes.getStatus());
                    scmEstimateQuotes.setStatusReason(scmSupplierQuotes.getStatusReason());
                    scmEstimateQuotesService.updateScmEstimateQuotes(scmEstimateQuotes);
                }
            }
        }

        return rows;
    }

    @Override
    public String importData(List<ScmSupplierQuotes> list, boolean updateSupport, String operName, Long projectId) {
        if (StringUtils.isNull(list) || list.isEmpty())
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ScmSupplierQuotes item : list)
        {
//            item.setProjectId(projectId);
            if (item.getQuoteDate() == null){
                item.setQuoteDate(DateUtils.getNowDate());
            }
//            if (!scmSupplierQuotesMapper.selectScmImportInquiriesInList(item).isEmpty()){
//                continue;
//            }
//            scmSupplierQuotesMapper.insertScmSupplierQuotes( item);
            scmSupplierQuotesMapper.updateScmSupplierQuotes( item);
            successNum++;
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();

    }
}
